<?php

namespace app\admin\controller;

use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use app\common\model\Acct;
use app\common\model\Admin;
use app\common\model\Category as CategoryModel;
use app\common\model\CategoryInfo;
use app\common\model\shop\Goods;
use app\common\model\shop\goods\Acct as GoodsAcct;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 分类管理
 *
 * @icon   fa fa-list
 * @remark 用于管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Category extends Backend
{

    /**
     * @var \app\common\model\Category
     */
    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];
    protected $acctLimit = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\common\model\Category');
        if (isset($this->request->param()['custom']['type']) && $this->request->param()['custom']['type'] == 'wl') {
            $this->acctLimit = false;
        }
        $tree = Tree::instance();
        $typeList = CategoryModel::getTypeList();
        if ($this->auth->isSuperAdmin()) {
            unset($typeList['distribution']);
            unset($typeList['ann_category']);
        } else {
            unset($typeList['wl']);
            unset($typeList['distribution']);
            unset($typeList['material']);
            $ids = CategoryInfo::where('acct_id', $this->auth->acct_id)->column('category_id');
            $this->model->whereIn('id', $ids);
        }
        $tree->init(collection($this->model->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }

        $uids = AuthGroupAccess::where('group_id', 10)->column('uid');
        $adminlist = Admin::whereIn('id', $uids)->select();

        $this->view->assign("adminlist", $adminlist);
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("typeList", $typeList);
        $this->view->assign("parentList", $categorydata);
        $this->assignconfig('typeList', $typeList);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $type = $this->request->request("type");
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");

            //构造父类select列表选项数据
            $list = [];

            foreach ($this->categorylist as $k => $v) {
                if ($search) {
                    if ($v['type'] == $type && stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false) {
                        if ($type == "all" || $type == null) {
                            $list = $this->categorylist;
                        } else {
                            $list[] = $v;
                        }
                    }
                } else {
                    if ($type == "all" || $type == null) {
                        $list = $this->categorylist;
                    } elseif ($v['type'] == $type) {
                        $list[] = $v;
                    }
                }
            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->view->assign('type', $type);
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        if ($this->acctLimit) {
            $params['acct_id'] = $this->auth->acct_id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            if ($result) {
                CategoryInfo::create([
                    'category_id' => $this->model->id,
                    'acct_id' => $this->auth->acct_id
                ], true);
            }
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {

            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if (isset($params['pid']) && $params['pid'] != $row['pid']) {
                    $childrenIds = Tree::instance()->init(collection(\app\common\model\Category::select())->toArray())->getChildrenIds($row['id'], true);
                    if (in_array($params['pid'], $childrenIds)) {
                        $this->error(__('Can not change the parent to child or itself'));
                    }
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }

                    $result = $row->allowField(true)->save($params);
                    if ($row->pid > 0) {
                        $info_ids =  CategoryInfo::where('category_id', $ids)->column('acct_id');
                        $acct_ids = $params['acct_ids'];
                        foreach ($info_ids as $key => $value) {
                            if (!in_array($value, $acct_ids)) {
                                CategoryInfo::where('category_id', $ids)->where('acct_id', $value)->delete();
                                continue;
                            }
                        }
                        // $goods_list = Goods::where('category_id', $ids)->where('custom', 0)->select();
                        foreach ($params['acct_ids'] as $k => $vv) {
                            $info = CategoryInfo::get([
                                'category_id' => $ids,
                                'acct_id' => $vv
                            ]);
                            if (!$info) {
                                CategoryInfo::create([
                                    'category_id' => $ids,
                                    'acct_id' =>  $vv
                                ], true);
                            }
                            // foreach ($goods_list as $goods) {
                            //     $goods->acct_ids = implode(',', $acct_ids);
                            //     $goods->save();
                            //     foreach ($acct_ids as $value) {
                            //         if (!in_array($value, $acct_ids)) {
                            //             GoodsAcct::where('goods_id', $goods->id)->where('acct_id', $value)->delete();
                            //         }
                            //     }
                            //     $has = GoodsAcct::where('goods_id', $goods->id)->where('acct_id',  $vv)->find();
                            //     if (!$has) {
                            //         GoodsAcct::create([
                            //             'goods_id' => $goods->id,
                            //             'acct_id' =>  $vv,
                            //             'price' => $goods->price,
                            //             'purchase_price' => $goods->purchase_price
                            //         ], true);
                            //     }
                            // }
                        }

                    }
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {

                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

    /**
     * 编辑
     */
    public function accredit($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->view->assign('ids', $ids);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        if ($this->acctLimit) {
            $params['acct_id'] = $this->auth->acct_id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            $ids = explode(',', $params['ids']);
            $acct_ids = explode(',', $params['admin_ids']);
            $ids = $this->model->whereIn('id', $ids)->where('pid', '>', 0)->column('id');
            foreach ($ids as $k => $v) {
                $info_ids =  CategoryInfo::where('category_id', $v)->column('acct_id');
                foreach ($info_ids as $key => $value) {
                    if (!in_array($value, $acct_ids)) {
                        CategoryInfo::where('category_id', $v)->where('acct_id', $value)->delete();
                        continue;
                    }
                }
                // $goods_list = Goods::where('category_id', $v)->where('custom', 0)->select();
                foreach ($acct_ids as $k => $vv) {
                    $info = CategoryInfo::get([
                        'category_id' => $v,
                        'acct_id' => $vv
                    ]);
                    if (!$info) {
                        CategoryInfo::create([
                            'category_id' => $v,
                            'acct_id' => $vv
                        ], true);
                    }
                    // foreach ($goods_list as $goods) {
                    //     $goods->acct_ids = implode(',', $acct_ids);
                    //     $goods->save();
                    //     foreach ($acct_ids as $value) {
                    //         if (!in_array($value, $acct_ids)) {
                    //             GoodsAcct::where('goods_id', $goods->id)->where('acct_id', $value)->delete();
                    //         }
                    //     }
                    //     $has = GoodsAcct::where('goods_id', $goods->id)->where('acct_id', $vv)->find();
                    //     if (!$has) {
                    //         $res = GoodsAcct::create([
                    //             'goods_id' => $goods->id,
                    //             'acct_id' => $vv,
                    //             'price' => $goods->price,
                    //             'purchase_price' => $goods->purchase_price
                    //         ], true);
                    //     }
                    // }
                }
            }
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success();
    }
}
